<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use OpenAI\Laravel\Facades\OpenAI;

class OpenAIService
{
    public function submitMessage($threadId, $userMessage)
    {
        try {
            return OpenAI::threads()->messages()->create($threadId, [
                'role' => 'user',
                'content' => $userMessage,
            ]);
        } catch (\OpenAI\Exceptions\ErrorException $e) {
            Log::error('Error adding message to thread: ' . $e->getMessage());
            throw $e;
        }
    }

    public function cancelRun($threadId, $runId)
    {
        try {
            OpenAI::threads()->runs()->cancel($threadId, $runId);
            Log::info("Active run $runId cancelled successfully.");
        } catch (\OpenAI\Exceptions\ErrorException $e) {
            Log::error('Error cancelling active run: ' . $e->getMessage());
            throw $e;
        }
    }

    public function createRun(string $threadId, array $parameters)
    {
        return OpenAI::threads()->runs()->create($threadId, $parameters);
    }

    public function waitOnRun($run, $threadId)
    {
        while (in_array($run->status, ["queued", "in_progress"])) {
            $run = OpenAI::threads()->runs()->retrieve($threadId, $run->id);
            sleep(1);
        }
        return $run;
    }

    public function getMessages($threadId, $order = 'asc', $messageId = null)
    {
        $params = [
            'order' => $order,
            'limit' => 10
        ];

        if ($messageId) {
            $params['after'] = $messageId;
        }

        return OpenAI::threads()->messages()->list($threadId, $params);
    }

    public function submitToolOutputs(string $threadId, string $runId, array $toolCalls)
    {
        try {
            $toolOutputs = [];
            foreach ($toolCalls as $toolCall) {
                $toolOutputs[] = [
                    'tool_call_id' => $toolCall['tool_call_id'],
                    'output' => $toolCall['result']
                ];
            }

            $response = OpenAI::threads()->runs()->submitToolOutputs($threadId, $runId, [
                'tool_outputs' => $toolOutputs,
            ]);
            return $response;
        } catch (\OpenAI\Exceptions\ErrorException $e) {
            Log::error('Error submitting tool outputs: ' . $e->getMessage());
            throw $e;
        }
    }
}
